package xyz.coolcsm.security.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import xyz.coolcsm.security.config.JsonResult;
import xyz.coolcsm.security.config.ResultTool;
import xyz.coolcsm.security.config.RsaKeyProperties;
import xyz.coolcsm.security.entity.SysRole;
import xyz.coolcsm.security.entity.SysUser;
import xyz.coolcsm.security.service.RedisService;
import xyz.coolcsm.security.service.SysUserInfoService;
import xyz.coolcsm.security.service.SysUserService;
import xyz.coolcsm.security.utils.JwtUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author 什锦
 * @since 2021-06-1
 */
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private SysUserService sysUserService;

    private RsaKeyProperties prop;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SysUserInfoService sysUserInfoService;

    public void setProp(RsaKeyProperties prop) {
        this.prop = prop;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //更新用户表上次登录时间、更新人、更新时间等字段
        User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUser sysUser = sysUserService.selectByName(userDetails.getUsername());
        sysUser.setLastLoginTime(new Date());
        sysUserService.update(sysUser);
        //此处还可以进行一些处理，比如登录成功之后可能需要返回给前台当前用户有哪些菜单权限，
        //进而前台动态的控制菜单的显示等，具体根据自己的业务需求进行扩展
        //返回前端的token，信息封装
        SysUser user = new SysUser();
        user.setUsername(userDetails.getUsername());
        user.setId(sysUser.getId());
        user.setNickName(sysUser.getNickName());
        user.setAvatar(sysUser.getAvatar());
        user.setEmail(sysUser.getEmail());
        Collection<? extends GrantedAuthority> collection = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        List<SysRole> sysRoles = new ArrayList<>();
        for (GrantedAuthority authority : collection) {
            SysRole sysRole = new SysRole();
            sysRole.setRoleName(authority.toString());
            sysRoles.add(sysRole);
        }
        user.setRoles(sysRoles);
        String token = JwtUtils.generateTokenExpireInMinutes(user, prop.getPrivateKey(), 24*60);

        //将用户的主体信息存入缓存
        redisService.set(user.getId().toString(),sysUserInfoService.getById(user.getId()));

        httpServletResponse.addHeader("Authorization", "Bearer " + token);
        //返回json数据
        JsonResult result = ResultTool.success();
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }
}

